/*
 * Copyright (C) 2009  Sylvain Maucourt (smaucourt@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 *
 */
package net.sylvek.where.server;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

import net.sylvek.where.entity.PMF;
import net.sylvek.where.entity.UserEntity;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class Uids extends CachedServlet {

    @SuppressWarnings("unchecked")
    private void process(String kind, String elements, Double lat, Double lon, PrintWriter writer) throws ServletException,
            IOException
    {

        int limit = 500;
        if (elements != null) {
            try {
                limit = Integer.valueOf(elements);
            } catch (NumberFormatException e) {
                limit = 500;
            }
        }

        PersistenceManager pm = PMF.get().getPersistenceManager();

        try {
            JsonArray result = new JsonArray();
            Query q = pm.newQuery(UserEntity.class);

            q.setRange(0, limit);
            q.setOrdering("update desc");

            Collection<UserEntity> c = null;
            if (kind != null && kind.equals("nearme") && lat != null && lon != null) {
                String hash = GeoHash.hash(lat, lon);
                q.declareParameters("String hash");
                q.setFilter("locationHash == hash");
                c = (Collection<UserEntity>) q.execute(hash);
            } else if (kind != null && kind.equals("online")) {
                q.setFilter("online == true");
                c = (Collection<UserEntity>) q.execute();
            } else {
                c = (Collection<UserEntity>) q.execute();
            }

            Iterator<UserEntity> i = c.iterator();
            while (i.hasNext()) {
                UserEntity u = i.next();
                String uid = UidHelper.getExternalUid(u.getUid());
                if (uid != null && !uid.trim().equals("")) {
                    result.add(new JsonPrimitive(Long.valueOf(uid)));
                }
            }

            writer.print(result.toString());
        } catch (Exception e) {
            JsonObject error = new JsonObject();
            error.addProperty("success", false);
            error.addProperty("error", e.getMessage());
            writer.print(error.toString());
        } finally {
            pm.close();
            writer.flush();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        String kind = req.getParameter("kind");
        String elements = req.getParameter("elements");
        String lat = req.getParameter("latitude");
        String lon = req.getParameter("longitude");
        process(kind, elements, Double.valueOf(lat), Double.valueOf(lon), resp.getWriter());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        String kind = req.getParameter("kind");
        String elements = req.getParameter("elements");
        String lat = req.getParameter("latitude");
        String lon = req.getParameter("longitude");

        if (lat == null || lon == null) {
            process(kind, elements, null, null, resp.getWriter());
        } else {
            process(kind, elements, Double.valueOf(lat), Double.valueOf(lon), resp.getWriter());
        }
    }

}
